package com.pks.datacenter.interceptor;

import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.pks.datacenter.common.WebContext;
import com.pks.datacenter.config.UnPermException;
import com.pks.util.UtilString;
import com.pks.web.context.BasicWebContext;
import com.pks.web.dto.ServiceResult;

@SuppressWarnings(value = {"unused"})
public class MyInterceptor implements HandlerInterceptor {

	private Logger logger = LoggerFactory.getLogger(MyInterceptor.class);
	
	private String loginUrl;
	private List<String> excludeUrls;

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//		return true;
		if (exclude(request)) {
			return true;
		}
		if (WebContext.getLoginUser(request) == null) {
			ServiceResult sr = ServiceResult.init(20001, "请重新登录");
			response.getWriter().write(ServiceResult.GSON_D.toJson(sr));
			return false;
		}
		return true;
	}

	private boolean exclude(HttpServletRequest arg0) {
		if (excludeUrls != null) {
			for (String exc : excludeUrls) {
				if (Pattern.matches(arg0.getContextPath() + exc, arg0.getRequestURI())) {
					return true;
				}
			}
		}
		return false;
	}

	private String initLoginUrl(HttpServletRequest arg0) {
		StringBuilder sb = new StringBuilder();
		sb.append(arg0.getContextPath());
		if (UtilString.isNotBlank(loginUrl)) {
			sb.append(loginUrl);
		}
		return sb.toString();
	}

	public String getLoginUrl() {
		return loginUrl;
	}

	public void setLoginUrl(String loginUrl) {
		this.loginUrl = loginUrl;
	}

	public List<String> getExcludeUrls() {
		return excludeUrls;
	}

	public void setExcludeUrls(List<String> excludeUrls) {
		this.excludeUrls = excludeUrls;
	}

}
